<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <!-- <el-form-item label="区域名称">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店名称">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="储值卡规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入储值卡规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:storeCardRule:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:storeCardRule:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:storeCardRule:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:storeCardRule:del']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="归属区域" align="center" prop="regionName">
        <template slot-scope="scope">
          <el-tooltip class="tooltip" placement="top">
            <div slot="content" style="max-width: 600px">
              {{ scope.row.regionNames === null ? "" : scope.row.regionNames }}
            </div>
            <div class="descStyle">
              {{ scope.row.regionNames === null ? "" : scope.row.regionNames }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="归属门店" align="center" prop="storeNames">
        <template slot-scope="scope">
          <el-tooltip class="tooltip" placement="top">
            <div slot="content" style="max-width: 600px">
              {{ scope.row.storeNames === null ? "" : scope.row.storeNames }}
            </div>
            <div class="descStyle">
              {{ scope.row.storeNames === null ? "" : scope.row.storeNames }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="储值卡名称" align="center" prop="ruleName" />
      <el-table-column label="折扣率" align="center" prop="discountRate" />
      <el-table-column label="充值金额" align="center" prop="topUp" />
      <el-table-column label="赠送金额" align="center" prop="gift" />

      <el-table-column label="赠送优惠券名称" align="center" prop="couponNames" />
      <el-table-column label="赠送优惠券数量" align="center" prop="couponNumber" />

      <el-table-column label="提成金额" align="center" prop="royalty" />
      <el-table-column label="规则说明" align="center" prop="remark">
        <template slot-scope="scope">
          <el-tooltip class="tooltip" placement="top">
            <div slot="content" style="max-width: 650px">
              {{ scope.row.remark === null ? "无" : scope.row.remark }}
            </div>
            <p class="descStyle">
              {{ scope.row.remark === null ? "无" : scope.row.remark }}
            </p>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="小程序端是否显示" align="center" prop="isShow">
        <template slot-scope="scope">
          <span>{{ scope.row.isShow == "1" ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.status == "1" ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />

      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="修改人" align="center" prop="updateBy" />


      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:storeCardRule:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleGround(scope.row, (status = 1))"
            v-hasPermi="['business:storeCardRule:start']"
            :disabled="scope.row.status === 1"
            >启用</el-button
          >
          <!-- <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleAddcrossStore(scope.row)"
            v-hasPermi="['business:memCardRule:open']">跨店规则</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleGround(scope.row, (status = 2))"
            v-hasPermi="['business:storeCardRule:disabled']"
            :disabled="scope.row.status === 2"
            >禁用</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:storeCardRule:del']"
            :disabled="scope.row.status === 1"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改门店对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="储蓄卡规则名称" prop="ruleName">
          <el-input
            v-model="form.ruleName"
            placeholder="请输入储蓄卡规则名称"
            style="width: 222px"
          />
        </el-form-item>
        <!-- <el-form-item label="储蓄卡封面" prop="img">
          <image-upload v-model="form.img" />
        </el-form-item> -->
        <el-form-item label="区域" prop="regionIds">
          <el-select
            clearable
            filterable
            multiple
            v-model="form.regionIds"
            @change="changeRegion"
          >
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="适用门店" prop="storeIds">
          <el-select
            clearable
            filterable
            multiple
            v-model="form.storeIds"
            @change="changeStore"
          >
            <el-option
              v-for="(item, index) of store"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="折扣率" prop="discountRate">
          <el-input
            v-model="form.discountRate"
            placeholder="折扣率"
            style="width: 222px"
          />
          <span style="color: red">（折扣率数值在 0~10 之间）</span>
        </el-form-item>
        <el-form-item label="充值金额" prop="topUp">
          <el-input
            v-model="form.topUp"
            placeholder="请输入充值金额"
            style="width: 222px"
          />
        </el-form-item>

        <el-form-item label="赠送方式" >
          <el-select clearable v-model="form.giveWay">
            <el-option label="赠送金额" value="1"></el-option>
            <el-option label="优惠券" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="赠送金额" v-if="form.giveWay == 1" prop="gift">
          <el-input
            v-model="form.gift"
            placeholder="请输入赠送金额"
            style="width: 222px"
          />
        </el-form-item>

        <el-form-item
          label="赠送数量"
          v-if="form.giveWay == 2"
          prop="giftNumber"
        >
          <el-input
            v-model="form.giftNumber"
            placeholder="请输入赠送数量"
            style="width: 222px"
          />
        </el-form-item>

        <el-form-item label="优惠券" v-if="form.giveWay == 2" prop="couponIds">
          <el-select multiple clearable v-model="form.couponIds">
            <el-option
              v-for="(item, index) of couponList"
              :key="index"
              :label="item.name"
              :value="item.id"
              >{{ item.name }}</el-option
            >
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="转赠数量" v-if="form.giveWay == 2">
          <el-input
            v-model="form.giveWayNum"
            placeholder="请输入转赠数量"
            style="width: 222px"
          />
        </el-form-item> -->

        <el-form-item label="提成金额">
          <el-input
            v-model="form.royalty"
            placeholder="请输入提成金额"
            style="width: 222px"
          />
        </el-form-item>
        <el-form-item label="规则说明" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入规则说明"
            style="width: 222px"
          />
        </el-form-item>
        <el-form-item label="小程序端是否显示" prop="isShow">
          <el-select clearable v-model="form.isShow">
            <el-option
              v-for="(item, index) of isShowList"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>

        <el-form-item label="退款比例" prop="refundRatio">
          <el-input v-model="form.refundRatio" placeholder="请输入退款比例1-100"    style="width: 222px" />
          <span style="color: red">（单位:%）</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 跨店规则 -->
    <el-dialog
      :title="title"
      :visible.sync="crossStore"
      width="600px"
      append-to-body
      @close="crossStoreClose"
    >
      <el-form
        ref="subForm"
        :model="subForm"
        :rules="subRules"
        label-width="120px"
      >
        <el-form-item label="适用区域" prop="regionId">
          <el-select
            clearable
            v-model="subForm.regionId"
            @change="changeSubRegion"
            multiple
          >
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="适用门店" prop="storeId">
          <el-select
            clearable
            v-model="subForm.storeId"
            @change="changeSubStore"
            multiple
          >
            <el-option
              v-for="(item, index) of subStore"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCross">确 定</el-button>
        <el-button @click="cancelCross">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCardRule,
  getCardRule,
  delCardRule,
  addCardRule,
  updateCardRule,
  listMemberRegion,
  listMemberStore,
  submitCross,
  cardRuleCouponList,
  getZyCouponEffectiveList,
} from "@/api/system/card/storeCardRule";

export default {
  name: "Store",
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        regionName: null,
        storeName: null,
        ruleName: null,
        // storeName: null,
        // phoneNumber: null,
        // province: null,
        // provinceString: null,
        // city: null,
        // cityString: null,
        // county: null,
        // countyString: null,
        // detail: null,
        // longitude: null,
        // latitude: null,
        // intro: null,
        // images: null,
        // status: null,
        // isInitiate: null,
        // openingTime: null,
        // closingTime: null,
      },
      // 表单参数
      form: {
        giveWay: "",
        couponIds: "",
        giftNumber: "",
        ruleName: "",
      },
      subForm: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "请输入会员卡规则名称", trigger: "blur" },
        ],
        regionId: [
          { required: true, message: "请填选适用区域", trigger: "blur" },
        ],
        giveWay: [{ required: true, message: "请选择", trigger: "blur" }],
        // gift: [{ required: true, message: "请输入", trigger: "blur" }],
        couponIds: [{ required: true, message: "请选择", trigger: "blur" }],
        storeIds: [
          { required: true, message: "请填选适用门店", trigger: "blur" },
        ],
        discountRate: [
          { required: true, message: "请输入折扣率", trigger: "blur" },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入个位数",
            trigger: "blur",
          },
        ],
        topUp: [
          { required: true, message: "请输入充值金额", trigger: "blur" },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "充值金额必须为2位小数或者整数",
            trigger: "blur",
          },
        ],
        // gift: [
        //   { required: true, message: '请输入价格', trigger: 'blur' },
        //   { pattern: /^[0-9]+$/, message: '价格必须为数字', trigger: 'blur' }
        // ],
        royalty: [
          { required: true, message: "请输入提成金额", trigger: "blur" },
          {
            pattern: /^[0-9]+$/,
            message: "提成金额必须为数字",
            trigger: "blur",
          },
        ],
        isShow: [
          { required: true, message: "请选择是否展示", trigger: "blur" },
        ],
      },
      subRules: {
        regionId: [
          { required: true, message: "请填选适用区域", trigger: "blur" },
        ],
        storeId: [
          { required: true, message: "请填选适用门店", trigger: "blur" },
        ],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      isShowList: [
        {
          key: 1,
          value: "是",
        },
        {
          key: 0,
          value: "否",
        },
      ],
      region: [],
      store: [],
      memberRuleId: "",
      subStore: [],
      crossStore: false,
      couponList: [],
    };
  },
  watch: {
    "form.regionIds": {
      handler: function (newVal) {
        if (Array.isArray(newVal) && newVal.length > 0) {
          const regionIds = newVal.join(",");
          this.$nextTick(() => {
            listMemberStore({ regionIds }).then((res) => {
              this.store = res.data.map((rItem) => {
                return {
                  key: rItem.id,
                  value: rItem.storeName,
                };
              });
            });
          });
        }
      },
    },
    // 'form.storeIds':{
    //    handler: function (newVal){
    //     if (newVal.length > 0) {
    //     const storeIds = newVal.join(",");
    //     this.$nextTick(() => {
    //       listitem({ storeIds }).then((res) => {
    //         this.project = res.data.map((rItem) => {
    //           return {
    //             key: rItem.id,
    //             value: rItem.itemName,
    //           };
    //         });
    //       });
    //     });
    //   }
    //   }
    // },
  },
  created() {
    this.getList();
    this.listMemberRegion();
  },
  methods: {
    //跨店规则提交
    submitCross() {
      this.$refs["subForm"].validate((valid) => {
        const params = {
          regionIds: this.subForm.regionId.join(","),
          storeIds: this.subForm.storeId.join(","),
          memberRuleId: this.memberRuleId,
        };
        console.log(params);
        if (valid) {
          if (this.memberRuleId != "") {
            submitCross(params).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.crossStore = false;
                this.getList();
              }
            });
          } else {
            submitCross(this.subForm).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.crossStore = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    //关闭跨店弹窗
    crossStoreClose() {
      this.$refs["subForm"].resetFields();
      this.memberRuleId = "";
    },
    cancelCross() {
      this.$refs["subForm"].resetFields();
      this.memberRuleId = "";
      this.crossStore = false;
    },
    //跨店门店
    changeSubStore(value) {
      console.log("跨店门店", value);
    },
    //跨店区域
    changeSubRegion(value) {
      console.log("跨店区域", value);
      const regionIds = value.join(",");
      console.log(regionIds);
      listMemberStore({ regionIds: regionIds }).then((res) => {
        this.subStore = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    //跨店规则
    handleAddcrossStore(row) {
      console.log("跨店规则", row);
      this.memberRuleId = row.id;
      this.crossStore = true;
    },
    listMemberRegion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      // const selectedOption = this.region.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.regionName = selectedValue;
      this.form.regionIds = value;
      if (value) {
        this.form.storeIds = [];
      }
    },
    changeStore(value) {
      // const selectedOption = this.store.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // this.form.storeName = selectedValue;
      // this.form.storeIds.push(value[0])
      // console.log(888, this.form.storeIds);
      this.getCoupon();
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listCardRule(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 优惠券
    getCoupon() {
      let obj = {
        getPath: 3,
        overLayUseType: 3,
        // useType: 2,
        // storeIds: this.form.storeIds.toString(),
      };
      getZyCouponEffectiveList(obj).then((res) => {
        this.couponList = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.store = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeIds: [], // 点击修改后再点击新增无法选中下拉框数据
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.store = [];
      this.open = true;
      this.title = "添加规则";
    },
    // 上下架
    handleGround(row, status) {
      const params = {
        id: row.id,
        status: status,
      };
      this.$confirm(
        `此操作将${status === 1 ? "启用" : "禁用"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateCardRule(params).then((res) => {
            this.$message({
              type: "success",
              message: `${status === 1 ? "启用" : "禁用"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上下架",
          });
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCardRule(id).then((response) => {
        this.form = response.data;
        this.form.giveWay = response.data.giveWay + "";
        if (response.data.regionIds == "") {
          response.data.regionIds = null;
        } else {
          response.data.regionIds = response.data.regionIds
            .split(",")
            .map(Number);
        }

        if (response.data.couponIds == "" || response.data.couponIds == null) {
          response.data.couponIds = null;
        } else {
          response.data.couponIds = response.data.couponIds
            .split(",")
            .map(Number);
        }

        if (response.data.storeIds == "") {
          response.data.storeIds = null;
        } else {
          response.data.storeIds = response.data.storeIds
            .split(",")
            .map(Number);
        }
        this.getCoupon();
        console.log(this.form, "form");

        this.open = true;
        this.title = "修改规则";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.form.royalty = this.form.royalty == "" ? 0 : this.form.royalty;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            let obj = {};
            Object.assign(obj, this.form);
            obj.regionIds = this.form.regionIds
              ? this.form.regionIds.join(",")
              : null;
            obj.storeIds = this.form.storeIds
              ? this.form.storeIds.join(",")
              : null;
            obj.couponIds = this.form.couponIds
              ? this.form.couponIds.join(",")
              : null;
            updateCardRule(obj).then((res) => {
              if (res.code !== 200) return;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let obj = {};
            Object.assign(obj, this.form);
            obj.regionIds = this.form.regionIds
              ? this.form.regionIds.join(",")
              : null;
            obj.couponIds = this.form.couponIds
              ? this.form.couponIds.join(",")
              : null;

            obj.storeIds = this.form.storeIds
              ? this.form.storeIds.join(",")
              : null;
            addCardRule(obj).then((res) => {
              if (res.code !== 200) return;
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除规则编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCardRule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
.descStyle {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.tooltip {
  max-width: 650px;
}
</style>
